package com.cs.gateway.filter;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 登录拦截器
 */
@Component
@Slf4j
public class LoginFilter implements GlobalFilter {

    /**
     * 这段代码的作用是在用户请求进入网关时，对请求进行拦截
     * 验证用户是否已登录，如果已登录则将用户的登录id存储在请求的Header中，
     * 以便后续服务可以获取到用户信息。如果未登录，则会抛出异常
     */
    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();
        String url = request.getURI().getPath();
        log.info("日志->LoginFilter->filter->url->{}", url);
        if (url.equals("/user/doLogin")) {
            return chain.filter(exchange);
        }
        //TODO: 5.27 这块有问题，后期处理，暂时把loginId的值定死
//        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
//        String loginId = (String) tokenInfo.getLoginId();
        String loginId = "ozgZZ6mDeHXaIR3DfjZ7KhUNNSZM";
        if (StringUtils.isBlank(loginId)) {
            throw new Exception("未获取到用户信息");
        }
        mutate.header("loginId", loginId);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }
}
